package buffer

import (
	"bytes"
	"sync"
)

type Buffer struct {
	buf bytes.Buffer
	sync.RWMutex
}

func (b *Buffer) Read(p []byte) (n int, err error) {
	b.Lock()
	defer b.Unlock()
	n = len(p)
	byts := b.buf.Bytes()
	if n <= b.buf.Len() {
		copy(p, byts)
		b.buf.Reset()
		b.buf.Write(byts[n:])
		return
	} else {
		n = b.buf.Len()
		copy(p, byts)
		b.buf.Reset()
		return
	}
}

func (b *Buffer) Write(byts []byte) (int, error) {
	b.Lock()
	defer b.Unlock()
	return b.buf.Write(byts)
}

func (b *Buffer) Bytes() []byte {
	b.RLock()
	defer b.RUnlock()
	return b.buf.Bytes()
}

func (b *Buffer) WriteString(s string) (n int, err error) {
	b.Lock()
	defer b.Unlock()
	return b.buf.WriteString(s)
}

func (b *Buffer) Len() int {
	b.RLock()
	defer b.RUnlock()
	return b.buf.Len()
}
